package org.springblade.common.config;


import com.plumelog.core.util.LogExceptionStackTrace;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.error.BladeRestExceptionTranslator;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.log.publisher.ErrorLogPublisher;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;
import org.springblade.core.tool.utils.UrlUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * User: Jackey
 * Date: 2022-06-16
 * Time: 09:09
 * Description: 自定义全局异常处理
 */
@Order
@Slf4j
@ControllerAdvice
public class CustomExcepiton extends BladeRestExceptionTranslator {


	@ExceptionHandler(Throwable.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public R handleError(Throwable e) {
		log.error("服务器异常", e);
		//发送服务异常事件
		ErrorLogPublisher.publishEvent(e, UrlUtil.getPath(WebUtil.getRequest().getRequestURI()));
		return R.fail(ResultCode.INTERNAL_SERVER_ERROR, ResultCode.INTERNAL_SERVER_ERROR.getMessage());
	}

	@ExceptionHandler(DataAccessException.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public R mysqlException(DataAccessException e) {
		log.error("数据库异常", e);
		ErrorLogPublisher.publishEvent(e, UrlUtil.getPath(WebUtil.getRequest().getRequestURI()));

		SQLException se = (SQLException) e.getCause();
		if (se instanceof SQLIntegrityConstraintViolationException) {
			return R.fail(ResultCode.INTERNAL_SERVER_ERROR, "数据库字段重复, 请联系管理员处理");
		}
		return R.fail(ResultCode.INTERNAL_SERVER_ERROR, "数据库操作失败! 请联系管理员");
	}

	@ExceptionHandler(ServiceException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R handleError(ServiceException e) {
		String[] args = new String[]{e.getResultCode().getMessage() + "\n" + LogExceptionStackTrace.erroStackTrace(e).toString()};
		log.warn("{}", args);
		return R.fail(e.getResultCode(), e.getMessage());
	}

}
